package org.example.boot.usercenter.config;

import io.jsonwebtoken.ExpiredJwtException;
import org.example.boot.usercenter.utils.JwtUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        // 1. 从请求头提取 Token
        String token = JwtUtils.extractToken(request);

        try {
            // 2. 验证 Token 有效性
            if (token != null && JwtUtils.validateToken(token)) {
                // 3. 解析 Token 获取用户标识（如 openid）
                String openid = JwtUtils.getTokenOpenid(token);

                // 4. 构建 Authentication 对象并存入 SecurityContext
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(openid, null, null);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } else {
                // Token 无效或不存在，直接返回 401
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的 Token");
                return;
            }
        } catch (ExpiredJwtException e) {
            // Token 过期处理
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token 已过期");
            return;
        } catch (Exception e) {
            // 其他异常（如签名错误）
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token 验证失败");
            return;
        }

        // 5. 继续后续过滤器链
        filterChain.doFilter(request, response);
    }


}